/**
 * 校园二手书交易平台 - 前端JavaScript应用
 * 作者：Inscode AI
 * 创建时间：2025年12月
 * 功能：用户认证、书籍管理、订单处理、消息通信等
 */

// ==================== 全局变量 ====================
let currentUser = null;
let currentToken = localStorage.getItem('token');
let currentPage = 1;
let currentSort = 'publish_time';
let currentFilters = {};

// ==================== 初始化 ====================
document.addEventListener('DOMContentLoaded', function() {
    console.log('校园二手书交易平台前端应用初始化...');
    
    // 检查用户登录状态
    checkAuthStatus();
    
    // 绑定事件监听器
    bindEventListeners();
    
    // 初始化页面
    initializePage();
    
    // 加载初始数据
    loadInitialData();
});

// ==================== 用户认证 ====================
/**
 * 检查用户认证状态
 */
async function checkAuthStatus() {
    if (currentToken) {
        try {
            const response = await fetch('/api/auth/verify', {
                headers: {
                    'Authorization': `Bearer ${currentToken}`
                }
            });
            
            if (response.ok) {
                const data = await response.json();
                currentUser = data.user;
                updateUIForLoggedInUser();
            } else {
                // Token无效，清除本地存储
                localStorage.removeItem('token');
                currentToken = null;
            }
        } catch (error) {
            console.error('认证检查失败:', error);
            localStorage.removeItem('token');
            currentToken = null;
        }
    }
}

/**
 * 用户登录
 */
async function performLogin() {
    const username = document.getElementById('loginUsername').value.trim();
    const password = document.getElementById('loginPassword').value;
    
    if (!username || !password) {
        showAlert('请输入用户名和密码', 'warning');
        return;
    }
    
    try {
        const response = await fetch('/api/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });
        
        const data = await response.json();
        
        if (data.success) {
            // 保存token和用户信息
            currentToken = data.token;
            currentUser = data.user;
            localStorage.setItem('token', currentToken);
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('loginModal'));
            modal.hide();
            
            // 更新UI
            updateUIForLoggedInUser();
            showAlert('登录成功！', 'success');
            
            // 刷新当前页面
            location.reload();
        } else {
            showAlert(data.message || '登录失败', 'danger');
        }
    } catch (error) {
        console.error('登录失败:', error);
        showAlert('登录失败，请稍后重试', 'danger');
    }
}

/**
 * 用户注册
 */
async function performRegister() {
    const formData = {
        username: document.getElementById('regUsername').value.trim(),
        password: document.getElementById('regPassword').value,
        email: document.getElementById('regEmail').value.trim(),
        phone: document.getElementById('regPhone').value.trim(),
        student_number: document.getElementById('regStudentNumber').value.trim(),
        real_name: document.getElementById('regRealName').value.trim(),
        college: document.getElementById('regCollege').value,
        major: document.getElementById('regMajor').value.trim(),
        enrollment_year: parseInt(document.getElementById('regEnrollmentYear').value)
    };
    
    // 验证必填字段
    const requiredFields = ['username', 'password', 'email', 'phone', 'student_number', 'real_name', 'college', 'major', 'enrollment_year'];
    for (let field of requiredFields) {
        if (!formData[field]) {
            showAlert(`请填写${getFieldName(field)}`, 'warning');
            return;
        }
    }
    
    // 验证用户名格式
    if (!/^[a-zA-Z0-9_]{3,20}$/.test(formData.username)) {
        showAlert('用户名格式不正确，只能包含字母、数字和下划线，长度3-20位', 'warning');
        return;
    }
    
    // 验证密码长度
    if (formData.password.length < 6) {
        showAlert('密码长度至少6位', 'warning');
        return;
    }
    
    // 验证邮箱格式
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
        showAlert('邮箱格式不正确', 'warning');
        return;
    }
    
    // 验证手机号格式
    if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
        showAlert('手机号格式不正确', 'warning');
        return;
    }
    
    try {
        const response = await fetch('/api/auth/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });
        
        const data = await response.json();
        
        if (data.success) {
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('registerModal'));
            modal.hide();
            
            showAlert('注册成功！请登录', 'success');
            
            // 清空表单
            document.getElementById('registerForm').reset();
            
            // 显示登录模态框
            setTimeout(() => {
                new bootstrap.Modal(document.getElementById('loginModal')).show();
            }, 1000);
        } else {
            showAlert(data.message || '注册失败', 'danger');
        }
    } catch (error) {
        console.error('注册失败:', error);
        showAlert('注册失败，请稍后重试', 'danger');
    }
}

/**
 * 用户登出
 */
function logout() {
    localStorage.removeItem('token');
    currentToken = null;
    currentUser = null;
    updateUIForLoggedOutUser();
    showAlert('已退出登录', 'info');
    showPage('home');
}

/**
 * 更新已登录用户UI
 */
function updateUIForLoggedInUser() {
    if (!currentUser) return;
    
    const userNav = document.getElementById('userNav');
    userNav.innerHTML = `
        <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown">
                <i class="fas fa-user me-1"></i>${currentUser.username}
            </a>
            <ul class="dropdown-menu dropdown-menu-end">
                <li><a class="dropdown-item" href="#" onclick="showPage('profile')">
                    <i class="fas fa-user me-2"></i>个人中心
                </a></li>
                <li><a class="dropdown-item" href="#" onclick="showPage('orders')">
                    <i class="fas fa-shopping-cart me-2"></i>我的订单
                </a></li>
                <li><a class="dropdown-item" href="#" onclick="showPage('messages')">
                    <i class="fas fa-envelope me-2"></i>消息中心
                </a></li>
                <li><hr class="dropdown-divider"></li>
                <li><a class="dropdown-item text-danger" href="#" onclick="logout()">
                    <i class="fas fa-sign-out-alt me-2"></i>退出登录
                </a></li>
            </ul>
        </li>
    `;
    
    // 加载未读消息数量
    loadUnreadMessageCount();
}

/**
 * 更新未登录用户UI
 */
function updateUIForLoggedOutUser() {
    const userNav = document.getElementById('userNav');
    userNav.innerHTML = `
        <li class="nav-item">
            <a class="nav-link" href="#" onclick="showLoginModal()">
                <i class="fas fa-sign-in-alt me-1"></i>登录
            </a>
        </li>
        <li class="nav-item">
            <a class="nav-link" href="#" onclick="showRegisterModal()">
                <i class="fas fa-user-plus me-1"></i>注册
            </a>
        </li>
    `;
}

// ==================== 页面导航 ====================
/**
 * 显示指定页面
 */
function showPage(pageName) {
    // 隐藏所有页面
    document.querySelectorAll('.page-content').forEach(page => {
        page.style.display = 'none';
    });
    
    // 显示指定页面
    const targetPage = document.getElementById(pageName + 'Page');
    if (targetPage) {
        targetPage.style.display = 'block';
        targetPage.classList.add('fade-in');
        
        // 更新导航栏激活状态
        updateNavActive(pageName);
        
        // 加载页面数据
        loadPageData(pageName);
    }
}

/**
 * 更新导航栏激活状态
 */
function updateNavActive(pageName) {
    document.querySelectorAll('.navbar-nav .nav-link').forEach(link => {
        link.classList.remove('active');
    });
    
    // 根据页面名称设置激活状态
    const activeLink = document.querySelector(`[onclick="showPage('${pageName}')"]`);
    if (activeLink) {
        activeLink.classList.add('active');
    }
}

/**
 * 加载页面数据
 */
async function loadPageData(pageName) {
    switch (pageName) {
        case 'home':
            await loadBooks();
            break;
        case 'orders':
            if (currentUser) {
                await loadOrders();
            } else {
                showLoginModal();
            }
            break;
        case 'messages':
            if (currentUser) {
                await loadMessages();
            } else {
                showLoginModal();
            }
            break;
        case 'profile':
            if (currentUser) {
                await loadProfile();
            } else {
                showLoginModal();
            }
            break;
    }
}

// ==================== 书籍相关功能 ====================
/**
 * 加载书籍列表
 */
async function loadBooks(page = 1) {
    try {
        // 构建查询参数
        const params = new URLSearchParams({
            page: page,
            limit: 12,
            sort_by: currentSort
        });
        
        // 添加筛选条件
        Object.keys(currentFilters).forEach(key => {
            if (currentFilters[key]) {
                params.append(key, currentFilters[key]);
            }
        });
        
        const response = await fetch(`/api/books?${params}`);
        const data = await response.json();
        
        if (data.success) {
            displayBooks(data.books);
            displayPagination(data.page, data.total_pages, data.total);
            currentPage = page;
        } else {
            showAlert('加载书籍失败', 'danger');
        }
    } catch (error) {
        console.error('加载书籍失败:', error);
        showAlert('加载书籍失败，请稍后重试', 'danger');
    }
}

/**
 * 显示书籍列表
 */
function displayBooks(books) {
    const booksList = document.getElementById('booksList');
    const resultCount = document.getElementById('resultCount');
    
    if (!books || books.length === 0) {
        booksList.innerHTML = `
            <div class="col-12">
                <div class="empty-state">
                    <i class="fas fa-book-open"></i>
                    <h5>暂无书籍</h5>
                    <p>还没有人发布书籍，快来发布第一本书吧！</p>
                </div>
            </div>
        `;
        resultCount.textContent = '共找到 0 本书籍';
        return;
    }
    
    booksList.innerHTML = books.map(book => `
        <div class="col-md-6 col-lg-4 mb-4">
            <div class="card book-card h-100" onclick="showBookDetail(${book.book_id})">
                <img src="${book.primary_image ? '/uploads/' + book.primary_image : 'https://via.placeholder.com/300x200?text=暂无图片'}" 
                     class="card-img-top" alt="${book.title}">
                <div class="card-body d-flex flex-column">
                    <h5 class="book-title" title="${book.title}">${book.title}</h5>
                    <div class="mb-2">
                        <span class="book-condition condition-${book.condition}">
                            ${getConditionText(book.condition)}
                        </span>
                    </div>
                    <div class="book-info mb-3">
                        <div><i class="fas fa-user me-1"></i>${book.seller_name}</div>
                        <div><i class="fas fa-university me-1"></i>${book.seller_college}</div>
                        <div><i class="fas fa-eye me-1"></i>${book.view_count} 次浏览</div>
                    </div>
                    <div class="mt-auto">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <span class="book-price">¥${book.price}</span>
                                ${book.original_price ? `<span class="book-original-price">¥${book.original_price}</span>` : ''}
                            </div>
                            <button class="btn btn-sm btn-outline-primary" onclick="event.stopPropagation(); favoriteBook(${book.book_id})">
                                <i class="fas fa-heart"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
    
    resultCount.textContent = `共找到 ${books.length} 本书籍`;
}

/**
 * 显示分页
 */
function displayPagination(currentPage, totalPages, total) {
    const pagination = document.getElementById('pagination');
    
    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }
    
    let html = '';
    
    // 上一页
    if (currentPage > 1) {
        html += `<li class="page-item">
            <a class="page-link" href="#" onclick="loadBooks(${currentPage - 1}); return false;">
                <i class="fas fa-chevron-left"></i>
            </a>
        </li>`;
    } else {
        html += `<li class="page-item disabled">
            <a class="page-link" href="#">
                <i class="fas fa-chevron-left"></i>
            </a>
        </li>`;
    }
    
    // 页码
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        html += `<li class="page-item ${i === currentPage ? 'active' : ''}">
            <a class="page-link" href="#" onclick="loadBooks(${i}); return false;">${i}</a>
        </li>`;
    }
    
    // 下一页
    if (currentPage < totalPages) {
        html += `<li class="page-item">
            <a class="page-link" href="#" onclick="loadBooks(${currentPage + 1}); return false;">
                <i class="fas fa-chevron-right"></i>
            </a>
        </li>`;
    } else {
        html += `<li class="page-item disabled">
            <a class="page-link" href="#">
                <i class="fas fa-chevron-right"></i>
            </a>
        </li>`;
    }
    
    pagination.innerHTML = html;
}

/**
 * 显示书籍详情
 */
async function showBookDetail(bookId) {
    try {
        const response = await fetch(`/api/books/${bookId}`);
        const data = await response.json();
        
        if (data.success) {
            const book = data.book;
            
            // 创建模态框内容
            const modalContent = `
                <div class="modal-header">
                    <h5 class="modal-title">${book.title}</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div id="bookImagesCarousel" class="carousel slide mb-3" data-bs-ride="carousel">
                                <div class="carousel-inner">
                                    ${book.images.map((img, index) => `
                                        <div class="carousel-item ${index === 0 ? 'active' : ''}">
                                            <img src="/uploads/${img}" class="d-block w-100" alt="${book.title}" style="max-height: 300px; object-fit: contain;">
                                        </div>
                                    `).join('')}
                                </div>
                                ${book.images.length > 1 ? `
                                    <button class="carousel-control-prev" type="button" data-bs-target="#bookImagesCarousel" data-bs-slide="prev">
                                        <span class="carousel-control-prev-icon"></span>
                                    </button>
                                    <button class="carousel-control-next" type="button" data-bs-target="#bookImagesCarousel" data-bs-slide="next">
                                        <span class="carousel-control-next-icon"></span>
                                    </button>
                                ` : ''}
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h4 class="text-danger mb-3">¥${book.price}</h4>
                            ${book.original_price ? `<p class="text-muted"><del>原价：¥${book.original_price}</del></p>` : ''}
                            
                            <div class="mb-3">
                                <span class="book-condition condition-${book.condition}">
                                    ${getConditionText(book.condition)}
                                </span>
                            </div>
                            
                            <div class="mb-3">
                                <h6>基本信息</h6>
                                <table class="table table-sm">
                                    <tr><td width="30%"><strong>作者</strong></td><td>${book.author || '-'}</td></tr>
                                    <tr><td><strong>出版社</strong></td><td>${book.publisher || '-'}</td></tr>
                                    <tr><td><strong>ISBN</strong></td><td>${book.isbn || '-'}</td></tr>
                                    <tr><td><strong>学院</strong></td><td>${book.college || '-'}</td></tr>
                                    <tr><td><strong>课程</strong></td><td>${book.course || '-'}</td></tr>
                                </table>
                            </div>
                            
                            <div class="mb-3">
                                <h6>卖家信息</h6>
                                <p><i class="fas fa-user me-2"></i>${book.seller_name}</p>
                                <p><i class="fas fa-university me-2"></i>${book.seller_college}</p>
                                <p><i class="fas fa-star me-2"></i>信誉分：${book.seller_reputation}</p>
                            </div>
                            
                            ${book.description ? `
                                <div class="mb-3">
                                    <h6>书籍描述</h6>
                                    <p>${book.description}</p>
                                </div>
                            ` : ''}
                            
                            <div class="mb-3">
                                <p class="text-muted">
                                    <i class="fas fa-eye me-1"></i>${book.view_count} 次浏览
                                    <i class="fas fa-heart ms-3 me-1"></i>${book.favorite_count} 人收藏
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                    ${currentUser && currentUser.user_id !== book.seller_id ? `
                        <button type="button" class="btn btn-primary" onclick="createOrder(${book.book_id})">
                            <i class="fas fa-shopping-cart me-1"></i>立即购买
                        </button>
                        <button type="button" class="btn btn-outline-primary" onclick="favoriteBook(${book.book_id})">
                            <i class="fas fa-heart me-1"></i>收藏
                        </button>
                    ` : ''}
                </div>
            `;
            
            // 创建并显示模态框
            const modal = new bootstrap.Modal(document.createElement('div'));
            modal._element.className = 'modal fade';
            modal._element.innerHTML = modalContent;
            document.body.appendChild(modal._element);
            
            modal.show();
            
            // 增加浏览数
            await fetch(`/api/books/${bookId}/view`, {
                method: 'POST'
            });
            
            // 模态框关闭后移除
            modal._element.addEventListener('hidden.bs.modal', function() {
                document.body.removeChild(modal._element);
            });
            
        } else {
            showAlert('获取书籍详情失败', 'danger');
        }
    } catch (error) {
        console.error('获取书籍详情失败:', error);
        showAlert('获取书籍详情失败，请稍后重试', 'danger');
    }
}

/**
 * 收藏书籍
 */
async function favoriteBook(bookId) {
    if (!currentUser) {
        showLoginModal();
        return;
    }
    
    try {
        const response = await fetch(`/api/books/${bookId}/favorite`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${currentToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            showAlert('收藏成功！', 'success');
            // 刷新书籍列表
            loadBooks(currentPage);
        } else {
            showAlert(data.message || '收藏失败', 'warning');
        }
    } catch (error) {
        console.error('收藏失败:', error);
        showAlert('收藏失败，请稍后重试', 'danger');
    }
}

/**
 * 搜索书籍
 */
function bindSearchEvents() {
    const searchForm = document.getElementById('searchForm');
    if (searchForm) {
        searchForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 收集搜索条件
            currentFilters = {
                keyword: document.getElementById('keyword').value.trim(),
                college: document.getElementById('college').value,
                condition: document.getElementById('condition').value,
                min_price: document.getElementById('minPrice').value,
                max_price: document.getElementById('maxPrice').value
            };
            
            // 执行搜索
            loadBooks(1);
        });
    }
}

/**
 * 重置搜索
 */
function resetSearch() {
    document.getElementById('searchForm').reset();
    currentFilters = {};
    loadBooks(1);
}

/**
 * 排序书籍
 */
function sortBooks(sortBy) {
    currentSort = sortBy;
    loadBooks(1);
}

// ==================== 订单相关功能 ====================
/**
 * 创建订单
 */
async function createOrder(bookId) {
    if (!currentUser) {
        showLoginModal();
        return;
    }
    
    const buyerMessage = prompt('请输入购买留言（可选）：');
    
    try {
        const response = await fetch('/api/orders', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${currentToken}`
            },
            body: JSON.stringify({
                book_id: bookId,
                buyer_message: buyerMessage || ''
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            showAlert('订单创建成功！', 'success');
            // 关闭书籍详情模态框
            const modals = document.querySelectorAll('.modal.show');
            modals.forEach(modal => {
                const bsModal = bootstrap.Modal.getInstance(modal);
                if (bsModal) bsModal.hide();
            });
            
            // 跳转到订单页面
            setTimeout(() => {
                showPage('orders');
            }, 1000);
        } else {
            showAlert(data.message || '创建订单失败', 'warning');
        }
    } catch (error) {
        console.error('创建订单失败:', error);
        showAlert('创建订单失败，请稍后重试', 'danger');
    }
}

/**
 * 加载用户订单
 */
async function loadOrders() {
    try {
        const response = await fetch('/api/orders', {
            headers: {
                'Authorization': `Bearer ${currentToken}`
            }
        });
        
        const data = await response.json();
        
        if (data.success) {
            displayOrders(data.orders);
        } else {
            showAlert('加载订单失败', 'danger');
        }
    } catch (error) {
        console.error('加载订单失败:', error);
        showAlert('加载订单失败，请稍后重试', 'danger');
    }
}

/**
 * 显示订单列表
 */
function displayOrders(orders) {
    const buyerOrdersList = document.getElementById('buyerOrdersList');
    const sellerOrdersList = document.getElementById('sellerOrdersList');
    
    if (!orders || orders.length === 0) {
        buyerOrdersList.innerHTML = '<div class="empty-state"><i class="fas fa-shopping-bag"></i><h5>暂无购买订单</h5></div>';
        sellerOrdersList.innerHTML = '<div class="empty-state"><i class="fas fa-store"></i><h5>暂无出售订单</h5></div>';
        return;
    }
    
    // 分离买家和卖家订单
    const buyerOrders = orders.filter(order => order.buyer_id === currentUser.user_id);
    const sellerOrders = orders.filter(order => order.seller_id === currentUser.user_id);
    
    buyerOrdersList.innerHTML = buyerOrders.length > 0 
        ? buyerOrders.map(order => createOrderCard(order, 'buyer')).join('')
        : '<div class="empty-state"><i class="fas fa-shopping-bag"></i><h5>暂无购买订单</h5></div>';
    
    sellerOrdersList.innerHTML = sellerOrders.length > 0
        ? sellerOrders.map(order => createOrderCard(order, 'seller')).join('')
        : '<div class="empty-state"><i class="fas fa-store"></i><h5>暂无出售订单</h5></div>';
}

/**
 * 创建订单卡片
 */
function createOrderCard(order, userType) {
    const statusClass = `status-${order.status}`;
    const statusText = getOrderStatusText(order.status);
    const bookSnapshot = typeof order.book_snapshot === 'string' 
        ? JSON.parse(order.book_snapshot) 
        : order.book_snapshot;
    
    let actionButtons = '';
    
    if (userType === 'buyer') {
        if (order.status === 'pending') {
            actionButtons = `
                <button class="btn btn-sm btn-outline-danger me-2" onclick="cancelOrder('${order.order_id}')">
                    <i class="fas fa-times me-1"></i>取消订单
                </button>
            `;
